package com.lb.shopguide.ui.view.search.adapters;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.lb.shopguide.R;
import com.lb.shopguide.ui.view.search.db.HistoryContract;


/**
 * Created by mauker on 19/04/2016.
 * <p>
 * Default adapter used for the suggestion/history ListView.
 */
public class AdapterSearchSuggest extends CursorAdapter {

    public AdapterSearchSuggest(Context context, Cursor cursor, int flags) {
        super(context, cursor, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.item_search_suggest, parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ListViewHolder vh = new ListViewHolder(view);
        view.setTag(vh);
        final String text = cursor.getString(cursor.getColumnIndexOrThrow(HistoryContract.HistoryEntry.COLUMN_QUERY));
//        boolean isHistory = cursor.getInt(cursor.getColumnIndexOrThrow(
//                HistoryContract.HistoryEntry.COLUMN_IS_HISTORY)) != 0;

        vh.tvContent.setText(text);
        vh.ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnCloseClickListener != null) {
                    mOnCloseClickListener.onCloseClick(text);
                }
            }
        });
    }

    @Override
    public Object getItem(int position) {
        String retString = "";

        // Move to position, get query
        Cursor cursor = getCursor();
        if (cursor.moveToPosition(position)) {
            retString = cursor.getString(cursor.getColumnIndexOrThrow(HistoryContract.HistoryEntry.COLUMN_QUERY));
        }

        return retString;
    }

    private class ListViewHolder {
        ImageView ivClear;
        TextView tvContent;

        public ListViewHolder(View convertView) {
            ivClear = convertView.findViewById(R.id.iv_clear);
            tvContent = convertView.findViewById(R.id.tv_str);
        }
    }

    public interface OnCloseClickListener {
        void onCloseClick(String searchWord);
    }

    private OnCloseClickListener mOnCloseClickListener;

    public void setOnCloseClickListener(OnCloseClickListener listener) {
        mOnCloseClickListener = listener;
    }
}
